<template>
  <div class="security-video-container">
    <!-- 顶部条件筛选  @conditionChange="selectGroupChange($event)"-->

    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false" v-show="blockShow">
        <template slot="conditions">
          <SelectAllSec
            :allowClear="true"
            v-model="orgCode"
            @response="blockResponse($event)"
            @change="blockChange($event)"
          >
          </SelectAllSec>
        </template>
        <template slot="operate">
          <a-button type="primary" @click="getNodeTreeList()"> 查询 </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="main">
      <div class="tree-container">
        <div class="header">
          <a-switch
            v-if="definitionVisible"
            checked-children="高清"
            un-checked-children="流畅"
            v-model="videoDefinition"
            @change="definitionChange"
          />
          <bj-icon-font
            v-if="operation"
            type="xinzenggenjiedian"
            color="#0068B7"
            :size="16"
            @click.native="handelTreeMenu('node')"
          ></bj-icon-font>
        </div>
        <div class="search">
          <a-input-search
            v-model="vedioName"
            placeholder="请输入视频关键词"
            style="width: 100%"
            @search="getNodeTreeList()"
          />
        </div>
        <div class="tree-data">
          <a-empty v-if="treeData.length == 0" />
          <a-tree
            v-else
            blockNode
            show-icon
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :replaceFields="{
              children: 'zhgdVideoNodeList',
              title: 'nodeName',
              key: 'id',
            }"
            @expand="onExpand"
            @select="onSelect"
          >
            <template
              slot="title"
              slot-scope="{
                zhgdVideoList,
                nodeName,
                videoName,
                id,
                popVisible,
                zhgdDeptCode,
              }"
            >
              <!-- title="选择视频播放位置" -->
              <a-popover
                v-if="videoSplitNum > 1"
                trigger="click"
                v-model="popVisible"
              >
                <div slot="title" class="popover-title">
                  <div>选择视频播放位置</div>
                  <div>
                    <bj-icon-font
                      @click.native.stop="popoverClose(id)"
                      type="close"
                    >
                    </bj-icon-font>
                  </div>
                </div>
                <div
                  slot="content"
                  class="box-wrap"
                  :class="{
                    'box-warp-4': videoSplitNum == 4,
                    'box-warp-9': videoSplitNum == 9,
                  }"
                >
                  <div
                    class="box"
                    :class="{ act: selectI === i }"
                    v-for="(v, i) in videoSplitNum"
                    :key="i"
                    @click="selectVideo(id, i)"
                    @mouseenter="selectI = i"
                    @mouseleave="selectI = ''"
                  >
                    {{ i + 1 }}
                  </div>
                </div>
                <span id="popli" :title="nodeName || videoName">
                  {{ nodeName || videoName }}
                </span>
              </a-popover>
              <span v-else :title="nodeName || videoName">
                {{ nodeName || videoName }}
              </span>
              <span class="operate">
                <bj-icon-font
                  v-if="nodeName && operation"
                  type="xinzengzijiedian"
                  @click.native.stop="
                    handelTreeMenu('save', id, videoName, zhgdDeptCode)
                  "
                >
                </bj-icon-font>
                <bj-icon-font
                  v-if="operation"
                  @click.native.stop="
                    handelTreeMenu('update', id, videoName, zhgdDeptCode)
                  "
                  type="bianji"
                >
                </bj-icon-font>
                <bj-icon-font
                  v-if="zhgdVideoList.length == 0 && operation"
                  @click.native.stop="handelTreeMenu('delete', id, videoName)"
                  type="shanchu"
                >
                </bj-icon-font>
              </span>
            </template>
            <template slot="custom" slot-scope="{ videoName }">
              <img
                v-if="!videoName"
                class="menu-icon"
                src="@/assets/images/folder.png"
              />
              <img v-else class="menu-icon" src="@/assets/images/file.png" />
            </template>
          </a-tree>
        </div>
      </div>
      <div class="video-player-container">
        <div class="video-split">
          <bj-icon-font
            :class="{ on: videoSplitNum == 1 }"
            type="yige"
            @click.native="checkVideoNum(1)"
          ></bj-icon-font>
          <bj-icon-font
            type="sigongge"
            :class="{ on: videoSplitNum == 4 }"
            @click.native="checkVideoNum(4)"
          ></bj-icon-font>
          <bj-icon-font
            type="cd"
            :class="{ on: videoSplitNum == 9 }"
            @click.native="checkVideoNum(9)"
          ></bj-icon-font>
        </div>
        <a-empty v-if="videoList.length == 0" />
        <div v-else class="video-play">
          <div
            :class="{
              'cell-player-1': videoSplitNum == 1,
              'cell-player-4': videoSplitNum == 4,
              'cell-player-9': videoSplitNum == 9,
            }"
            v-for="(item, index) in videoList"
            :key="index"
            @dblclick="handeDoubleClick(item, idnex)"
          >
            <div
              class="rotate"
              @click="rotateClick(item)"
              v-if="item.rotate"
            ></div>
            <div class="video__name">
              {{ item.videoName }}
            </div>
            <!-- <VueVideo
              :autoplay="true"
              :videoSrc="item.hlsHd"
              :ref="'video_' + index"
              v-if="index != videoPlayIndex && item.hlsHd && !rotateVisible"
              :key="updateIndex"
            ></VueVideo> -->
            <!-- <iframe
              src="https://open.ys7.com/ezopen/h5/iframe?bSupporDoubleClickFull=1&url=ezopen://open.ys7.com/K62255411/1.hd.live&autoplay=1&audio=0&accessToken=at.dpbcku6c98ru1vxn7nml41w3ag5a5a4l-77d5yzsyv5-034gz2q-xictmlhbh&templete=0&id=videoPlay0&decoderVersion="
              frameborder="0"
              allowfullscreen
              width="100%"
              height="100%"
            ></iframe> -->
          </div>
        </div>
      </div>
    </div>
    <!-- 新增弹框 -->
    <video-model
      :visible.sync="modalVisible"
      :modelType="modelType"
      :rootZhgdCode="rootZhgdCode"
      :parentId="parentId"
      :editResource="editResource"
      :zhgdDeptCode="zhgdDeptCode"
    ></video-model>

    <!-- <rotate
      :visible.sync="rotateVisible"
      :title="rotateTitle"
      :id="rotateId"
    ></rotate> -->

    <!-- 视频角度旋转弹窗 -->
    <!-- <EzuikitModal
      :visible.sync="rotateVisible"
      :title="rotateTitle"
      :id="rotateId"
    ></EzuikitModal> -->

    <videoPtzModal
      :visible.sync="rotateVisible"
      :title="rotateTitle"
      :id="rotateId"
    ></videoPtzModal>
  </div>
</template>

<script>
import SelectAllSec from "@/components/wisdom-beam/security-app/SelectAllSec";
import VueVideo from "@/components/VueVideo";
import EZUIKitJs from "@/components/EZUIKitJs";
import rotate from "./components/rotate";
import EzuikitModal from "./components/EzuikitModal";
import videoPtzModal from "./components/videoPtzModal";
import VideoModel from "./components/VideoModel.vue";
import { notificationTip, addAttributeByKey, flatTreeData } from "@/utils";
import {
  getZhgdVideoNodeList,
  getZhgdVideoNodeDelete,
  getZhgdVideoDelete,
  getZhgdVideoDetail,
  setProjectVideo,
  getProjectVideoConfig,
  getAdjustAngle,
  superUserFlag,
} from "@/api/wisdom-beam/security-app.js";
import { movePreset, getVideoToken } from "@/api/monitor_video.js";
export default {
  components: {
    SelectAllSec,
    VueVideo,
    rotate,
    VideoModel,
    EzuikitModal,
    videoPtzModal,
    EZUIKitJs,
  },
  data() {
    return {
      popVisible: false,
      //标段
      orgCode: undefined,
      conditionsData: {},
      //视频关键词
      vedioName: "",
      //操作权限
      operation: false,
      //视频清晰度
      videoDefinition: false,
      definitionVisible: false,
      //左侧树列表
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      //新增弹窗-传参
      rootZhgdCode: "",
      parentId: "",
      modelType: "",
      modalVisible: false,
      editResource: "",
      zhgdDeptCode: "",
      //视频旋转弹窗-传参
      rotateVisible: false,
      rotateTitle: "",
      rotateId: "",
      //右侧视频区域
      videoSplitNum: 1,
      clickNum: 0,
      videoPlayIndex: -1,
      videoList: [],
      VideoListCopy: [{}, {}, {}, {}, {}, {}, {}, {}, {}],
      updateData: [],
      updateFlag: false,
      updateIndex: 0,
      selectI: "",
      selectedVideo: {},
      blockShow: false,
    };
  },
  mounted() {
    this.superUserFlag();
    this.getVideoVisible();
  },
  methods: {
    handeDoubleClick() {},

    //popover关闭
    popoverClose(id) {
      this.dealWithVisible(id, this.treeData);
    },

    blockResponse(val) {
      this.blockShow = val.length > 1;
    },

    blockChange(data) {
      //重置数据
      this.videoSplitNum = 1;
      this.clickNum = 0;
      this.videoPlayIndex = -1;
      this.videoList = [];
      this.VideoListCopy = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
      this.updateFlag = false;
      this.updateData = [];
      this.selectedKeys = [];
      this.autoExpandParent = false;
      this.expandedKeys = [];
      this.getNodeTreeList();
    },

    //查询用户操作权限
    superUserFlag() {
      return new Promise((resolve, reject) => {
        superUserFlag()
          .then((res) => {
            let { data } = res;
            this.operation = data?.result || false;
            resolve();
          })
          .catch((_) => {
            this.operation = false;
            reject();
          });
      });
    },
    //查询高清、标清操作权限
    getVideoVisible() {
      return new Promise((resolve, reject) => {
        getProjectVideoConfig()
          .then((res) => {
            let { data } = res;
            this.definitionVisible = data?.result?.buttonShowFlag || false;
            if (data?.result?.type == 1) this.videoDefinition = true;
            else this.videoDefinition = false;
            resolve();
          })
          .catch((_) => {
            this.definitionVisible = false;
            this.videoDefinition = false;
            reject();
          });
      });
    },
    //查询角度权限
    getAdjustAngle(id) {
      return new Promise((resolve, reject) => {
        getAdjustAngle({ vedioId: id })
          .then((res) => {
            resolve(res);
          })
          .catch((_) => {
            reject(_);
          });
      });
    },
    //旋转弹框
    rotateClick(ev) {
      this.rotateTitle = ev.videoName;
      this.rotateId = ev.id;
      this.rotateVisible = true;
    },

    //指定【a-popover】挂载的 HTML 节点
    getContainer() {
      return document.getElementById("popli");
    },

    //处理选择的视频
    selectVideo(id, i) {
      this.dealWithVisible(id, this.treeData);
      let index = this.videoList.findIndex(
        (v) => v.id == this.selectedVideo.id
      );
      if (index != -1) {
        this.videoList[index] = {};
        this.VideoListCopy[index] = {};
      }
      this.getAdjustAngle(id)
        .then((res) => {
          this.$set(this.selectedVideo, "rotate", res.data.result || false);
          this.VideoListCopy[i] = this.selectedVideo;
          this.videoList[i] = this.selectedVideo;
          this.videoPlayIndex = i;
          setTimeout(() => {
            this.videoPlayIndex = -1;
          }, 100);
        })
        .catch();
    },

    //处理单选事件
    dealWithVisible(id, data, type) {
      for (let i = 0; i < data.length; i++) {
        if (type) {
          this.$set(data[i], "popVisible", false);
        } else {
          if (id == data[i].id) {
            this.$set(data[i], "popVisible", false);
          }
        }
        if (
          data[i].zhgdVideoNodeList &&
          Array.isArray(data[i].zhgdVideoNodeList)
        ) {
          this.dealWithVisible(id, data[i].zhgdVideoNodeList, type);
        }
      }
    },

    //视频清晰度切换
    definitionChange(e) {
      let type = e ? 1 : 2;
      return new Promise((resolve, reject) => {
        setProjectVideo(type)
          .then((res) => {
            this.getNodeTreeList();
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },

    //合并视频list 和 nodeList
    updeteTree(data) {
      return flatTreeData(data, "zhgdVideoNodeList")
        .map((v) => v.zhgdVideoList)
        .flat()
        .filter((v) => v);
    },

    //获取根节点树数据
    getNodeTreeList() {
      let { orgCode, vedioName } = this;
      getZhgdVideoNodeList({
        zhgdDeptCode: orgCode?.key ?? "",
        vedioName,
      })
        .then((res) => {
          let array = res.data.result || [];
          //合并视频list 和 node List
          let tree = this.dealTree(array);
          //处理租户树形数据
          let filterData = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            tree,
            "zhgdVideoNodeList"
          );
          this.treeData = filterData;
          //编辑-触发
          if (this.updateFlag) {
            this.updateIndex++;
            this.updateData = this.updeteTree(this.treeData);
            try {
              this.updateData.forEach((item) => {
                this.videoList.forEach((v) => {
                  if (item.id == v.id) {
                    v.hls = item.hls;
                    v.hlsHd = item.hlsHd;
                  }
                });
              });
            } catch (e) {}
          } else {
            //初始化-页面
            let video = this.updeteTree(this.treeData);

            if (video?.[0]) {
              this.videoList = [video?.[0]];
              this.VideoListCopy[0] = video?.[0];
              let id = this.videoList?.[0]?.id;

              this.selectedKeys = [id];
              this.expandedKeys = [id];

              this.getAdjustAngle(id)
                .then((res) => {
                  this.$set(
                    this.videoList?.[0],
                    "rotate",
                    res.data.result || false
                  );
                })
                .catch();
            } else {
              this.videoList = [];
            }
          }
        })
        .catch();
    },
    //合并视频list 和 nodeList
    dealTree(data) {
      let res = [];
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (!item.zhgdVideoList) item.zhgdVideoList = [];
        if (!item.zhgdVideoNodeList) item.zhgdVideoNodeList = [];
        if (
          item.zhgdVideoList.length != 0 ||
          item.zhgdVideoNodeList.length != 0
        ) {
          item.zhgdVideoNodeList = item.zhgdVideoNodeList.concat(
            item.zhgdVideoList
          );
          this.$set(item, "popVisible", false);
          res.push(item);
        } else {
          this.$set(item, "popVisible", false);
          res.push(item);
        }
        this.dealTree(item.zhgdVideoNodeList);
      }
      return res;
    },

    //树展开事件
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //树选择事件
    onSelect(selectedKeys, e) {
      let { hlsHd, id, videoName } = e.node.dataRef;
      this.selectedKeys = [id];
      if (this.videoSplitNum > 1 && videoName) {
        this.selectedVideo = e.node.dataRef;
        this.dealWithVisible(id, this.treeData, true);
        e.node.dataRef.popVisible = !e.node.dataRef.popVisible;
        return;
      }
      //视频存在则通过id查询视频详情
      if (hlsHd) {
        this.updateFlag = true;
        getZhgdVideoDetail(id)
          .then((res) => {
            let { data } = res;
            let videoResult = data?.result || {};
            if (videoResult) {
              this.getAdjustAngle(id)
                .then((ev) => {
                  this.$set(videoResult, "rotate", ev.data.result || false);
                  this.$set(e.node.dataRef, "rotate", ev.data.result || false);

                  this.videoList = [];
                  this.VideoListCopy = [{}, {}, {}, {}, {}, {}, {}, {}, {}];

                  this.videoList[0] = e.node.dataRef;
                  this.VideoListCopy[0] = e.node.dataRef;
                  this.videoPlayIndex = 0;
                  setTimeout(async () => {
                    this.videoPlayIndex = -1;
                    //调整至初始位置
                    let {
                      intdata,
                      deviceSerialNumber,
                      channelNumber,
                      appkey,
                      secret,
                    } = e.node.dataRef;
                    if (intdata) {
                      let token = await this.getVideoToken(appkey, secret);
                      let params = {
                        accessToken: token,
                        deviceSerial: deviceSerialNumber,
                        channelNo: channelNumber,
                        index: intdata,
                      };
                      this.movePreset(params);
                    }
                  }, 100);
                })
                .catch();
            }
          })
          .catch();
      }
    },

    //调用预置点
    async movePreset(params = {}) {
      movePreset(params).then((res) => {
        console.log(res);
      });
    },

    getVideoToken(appKey = "", appSecret = "") {
      return new Promise((resolve, reject) => {
        getVideoToken({
          appKey,
          appSecret,
        })
          .then((res) => {
            let { data } = res;
            resolve(data?.accessToken || "");
          })
          .catch((_) => {
            reject("");
          });
      });
    },

    //判断当前点击的视频是否已经存在右侧的播放列表中
    isHasPlay(id) {
      return (
        this.videoList.filter((item, index) => {
          return item.id == id;
        }).length > 0
      );
    },
    //分割默认9个视频
    splitNineVideo() {
      this.videoList = this.VideoListCopy.filter((v, index) => {
        return index < this.videoSplitNum;
      });
    },
    //手动切换视频展示个数
    checkVideoNum(num) {
      this.updateFlag = true;
      this.videoSplitNum = num;
      this.splitNineVideo();
    },
    //左侧树菜单操作事件
    handelTreeMenu(type, id, videoName, zhgdDeptCode) {
      this.updateFlag = true;
      this.dealWithVisible(id, this.treeData, true);
      switch (type) {
        //新增跟节点
        case "node":
          let { orgCode } = this;
          if (!orgCode) {
            return notificationTip("success", "请先选择标段，再新增节点！");
          }
          this.modelType = type;
          this.rootZhgdCode = orgCode?.key ?? "";
          this.modalVisible = true;
          break;
        //新增子节点
        case "save":
          this.modelType = type;
          this.rootZhgdCode = "";
          this.parentId = id;
          this.modalVisible = true;
          this.zhgdDeptCode = zhgdDeptCode;
          break;
        //编辑
        case "update":
          this.modelType = type;
          this.rootZhgdCode = "";
          this.parentId = id;
          if (videoName) {
            this.editResource = "2";
          } else {
            this.editResource = "1";
          }
          this.modalVisible = true;
          this.zhgdDeptCode = zhgdDeptCode;
          break;
        //删除
        case "delete":
          let that = this;
          const h = this.$createElement;
          this.$confirm({
            title: "您确定删除所选内容?",
            content: "删除内容后,将无法恢复。",
            okText: "确定",
            okType: "primary",
            cancelText: "取消",
            centered: true,
            icon: () =>
              h("a-icon", {
                props: {
                  type: "question-circle",
                  theme: "filled",
                },
                style: "color:#FB5A5A",
              }),
            onOk() {
              if (videoName) {
                //视频删除
                getZhgdVideoDelete(id)
                  .then((res) => {
                    notificationTip("success", "删除成功！");
                    //处理右侧视频区域数据
                    that.videoList.forEach((item, index) => {
                      if (id == item.id) {
                        that.videoList.splice(index, 1);
                        that.videoList.push({});
                      }
                    });
                    let videoIndex = (that.VideoListCopy || []).findIndex(
                      (item) => item.id == id
                    );
                    that.VideoListCopy.splice(videoIndex, 1);
                    that.VideoListCopy.push({});
                    let length = (that.VideoListCopy || []).findIndex(
                      (item) => JSON.stringify(item) == "{}"
                    );
                    that.clickNum = length;
                    that.getNodeTreeList();
                  })
                  .catch();
              } else {
                //节点删除
                getZhgdVideoNodeDelete(id)
                  .then((res) => {
                    notificationTip("success", "删除成功！");
                    that.getNodeTreeList();
                  })
                  .catch((_) => {});
              }
            },
            onCancel() {},
          });
          break;
        default:
          break;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.security-video-container {
  box-sizing: border-box;
  height: 100%;
  .flex();
  flex-direction: column;
  padding: 0 0 10px 10px;
  overflow: hidden;
  .main {
    flex: 1;
    .flex();
    margin: 10px 10px 0 0;
    overflow: hidden;
    .tree-container {
      width: 340px;
      background-color: #fff;
      .flex();
      flex-direction: column;
      box-sizing: border-box;
      padding: 0px 15px 20px;
      .header {
        margin: 10px 0;
        .flex();
        align-items: center;
        justify-content: flex-end;
        /deep/.ant-switch {
          margin-right: 20px;
        }
        .bj-icon {
          cursor: pointer;
        }
      }
      .search {
        padding: 6px 0 6px 0;
      }
      .tree-data {
        flex: 1;
        height: 100%;
        .custom-scrollbar();
        /deep/.ant-tree {
          li {
            width: 100%;
            .ant-tree-node-content-wrapper {
              position: relative;
              width: calc(100% - 34px);
              .ant-tree-title {
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                display: inline-block;
                max-width: calc(100% - 90px);
              }
            }
          }
        }
        .operate {
          position: absolute;
          top: 0;
          right: 0;
        }
        .bj-icon {
          margin-right: 5px;
        }
      }
    }
    .video-player-container {
      background-color: #fff;
      margin-left: 2px;
      flex: 1;
      .flex();
      flex-direction: column;
      padding: 0 10px 10px 10px;
      position: relative;
      box-sizing: border-box;
      .video-split {
        .flex();
        justify-content: flex-end;
        align-items: center;
        margin: 10px 20px;
        /deep/.bj-icon {
          font-size: 24px;
          cursor: pointer;
          margin-right: 10px;
          &:last-of-type {
            margin-right: 0px;
          }
          &.on {
            color: var(--primary-color) !important;
          }
        }
      }
      .video-play {
        flex: 1;
        overflow: hidden;
        .flex();
        flex-wrap: wrap;
        justify-content: space-between;
        .rotate {
          position: absolute;
          right: 26px;
          top: 26px;
          width: 56px;
          height: 56px;
          z-index: 999;
          background: url("https://jszhgd.cn/static/pc/security-app/rotate.png")
            no-repeat center center;
          background-size: 100% auto;
          cursor: pointer;
        }
        .video__name {
          font-size: 18px;
          font-family: Microsoft YaHei;
          font-weight: bold;
          color: #fff;
          overflow: hidden;
          position: absolute;
          bottom: 12%;
          left: 12px;
          z-index: 999;
        }
        .cell-player-4 {
          width: 50%;
          height: 50%;
          position: relative;
          border: 1px solid #fff;
          background: #000;
        }
        .cell-player-1 {
          width: 100%;
          height: 100%;
          position: relative;
          border: 1px solid #fff;
          background: #000;
        }
        .cell-player-9 {
          width: 33.3333%;
          height: 33.3333%;
          position: relative;
          border: 1px solid #fff;
          background: #000;
        }
      }
    }
  }
}
#popli {
  display: inline-block;
}
.popover-title {
  .flex();
  align-items: center;
  justify-content: space-between;
  .bj-icon {
    cursor: pointer;
  }
}
.box-wrap {
  .flex();
  flex-wrap: wrap;
  width: 180px;
  box-sizing: border-box;
  .box {
    width: 32px;
    height: 32px;
    background: #d7ddec;
    border-radius: 4px;
    font-size: 20px;
    color: #fff;
    text-align: center;
    line-height: 32px;
    margin: 4px;
    cursor: pointer;
    &.act {
      background: var(--primary-color);
    }
  }
  &.box-warp-4 {
    padding: 0 50px;
  }
  &.box-warp-9 {
    padding: 0 30px;
  }
}
</style>
